#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define COMMAND_LEN 1024
#define ARGV_LEN 128 
const char* SEP = " ";
//#define Debug 1 //测试是否正确分割进argv

char pwd[1024];
int lastcode = 0;
char* getUSER()
{
    char* ret = getenv("USER");
    if(ret)
        return ret; 
    else return NULL;
}
char* getHOSTNAME()
{
    char* ret = getenv("HOSTNAME");
    if(ret)
        return ret; 
    else return NULL; //这样不好，可能会发生空指针的解引用
}   
char* getPWD()
{
    char* ret = getenv("PWD");
    if(ret)
        return ret; 
    else return NULL;
}   
void printCommand()
{
    printf("[%s@%s %s]# ", getUSER(), getHOSTNAME(), getPWD());
}
int getCommand(char* command, char* argv[])
{
    //scanf("%s", command); 有空格就不行，只能输入一个字符串
    fgets(command, COMMAND_LEN, stdin);
    //分割字符串
    command[strlen(command) - 1] = '\0'; 
    int argc = 0;
    argv[argc++] = strtok(command, SEP);
    while(argv[argc++] = strtok(NULL, SEP));

#ifdef Debug
    for(size_t i = 0; argv[i]; i++)
        printf("%d: %s\n", i, argv[i]);
#endif
    return argc;
}
char* getHomePath()
{
    char* homepath = getenv("HOME");
    return homepath; //和老师不一样，我觉得直接return
}
void cd(char* path)
{
    chdir(path);//更改当前的进程的工作目录
    char* tmp[1024]; //sizeof是应该运算符
    getcwd(tmp, sizeof tmp);//获取当前进程的工作目录
    sprintf(pwd, "PWD=%s", tmp);//通过覆盖PWD环境变量的方法更改命令提示符
    putenv(pwd);
}
int fatherExcuteCommand(char* argv[])
{
    if(strcmp(argv[0], "cd") == 0)
    {
        char* path = NULL;
        if(argv[1] == NULL) path = getHomePath();
        else path = argv[1]; //这也是要检查的，这里略写
        cd(path);
        return 1;
    }
    else if(strcmp(argv[0], "export") == 0)
    {
        if(argv[1] == NULL) return 1;
        putenv(argv[1]);//覆盖bug
        return 1;
    }
    else if(strcmp(argv[0], "echo") == 0)
    {
        if(argv[1] == NULL)
            printf("\n");
        else if(*argv[1] == '$' && strlen(argv[1]) > 1)
        {
            char* str = argv[1] + 1;
            if(strcmp(str, "?") == 0)
            {
                printf("%d\n", lastcode);
                lastcode = 0;
            }
            else
            {
                char* env = getenv(str);
                if(env) printf("%s\n", env);
                else printf("\n");
            }
        }
        else
            printf("%s\n", argv[1]);
        return 1;
    }
    else return 0;
}
void childExcuteCommand(char* argv[])
{
    pid_t id = fork();
    if(id == 0)
    {
        execvp(argv[0], argv);
        //错误执行exit
        exit(1);
    }
    else
    {
        int status = 0;
        pid_t rid = waitpid(id, &status, 0);
        //if(id == rid)
       if(rid > 0)
           lastcode = WEXITSTATUS(status);
    }
}
int main()
{
    while(1)
    {
        char command[COMMAND_LEN];
        char* argv[ARGV_LEN];
        //打印命令行
        printCommand();
        //读取输入，即命令行参数
        int n = getCommand(command, argv);
        if(n == 0) continue;//输入回车，重新跑
        
        //father执行内建命令
        n = fatherExcuteCommand(argv);
        if(n) continue;//内建命令

        //father fork child 执行命令
        childExcuteCommand(argv);
    }
}
